package com.example.telesys.predicates;

import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

/**
 * 注意这是自定义的断言工厂
 * 1. 类的命名必须为 关键字+RoutePredicateFactory
 * 其中关键字必须对于配置文件Predicates数组中的【关键字】配置
 * 2. 并且必须集成AbstractXXX<配置类>
 */
//@Component
public class AgeRoutePredicateFactory extends AbstractRoutePredicateFactory<AgeRoutePredicateFactory.Config> {

    public AgeRoutePredicateFactory() {
        super(AgeRoutePredicateFactory.Config.class);

    }

    // 将配置文件中的值按返回集合的顺序，赋值给配置类的属性上
    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList(new String[]{"minAge", "maxAge"});
    }

    // 断言
    @Override
    public Predicate<ServerWebExchange> apply(AgeRoutePredicateFactory.Config config) {

        //Lambda表达式
        return (ServerWebExchange serverWebExchange) -> {
            // TODO 获取URL中的请求参数age，判断是否满足[18, 60)
            String age = serverWebExchange.getRequest().getQueryParams().getFirst("age");
            if (StringUtils.isEmpty(age)) {
                return false;
            }
            if (!age.matches("[0-9]+")) {
                return false;
            }

            int iAge = Integer.parseInt(age);
            if (iAge >= config.minAge && iAge < config.maxAge) {
                return true;
            } else {
                return false;
            }
        };
    }

    // 配置类，属性用于接收配置文件中的值
    public static class Config {
        private int minAge;
        private int maxAge;

        public Config(int minAge, int maxAge) {
            this.minAge = minAge;
            this.maxAge = maxAge;
        }

        public Config() {
        }

        public int getMinAge() {
            return minAge;
        }

        public void setMinAge(int minAge) {
            this.minAge = minAge;
        }

        public int getMaxAge() {
            return maxAge;
        }

        public void setMaxAge(int maxAge) {
            this.maxAge = maxAge;
        }
    }
}
